<?php
/** 
 * Class collection
 * 
 */
class Collection {
	var $collection_id = false;
	var $c_name = '';
	var $c_info = '';
	var $c_user = false;
	var $db_fields = array();
	
	
	function Collection ($obj=false) {
		$this->table = TP."_collection";
		
		
		if(is_int($obj)) {
			$query="select * from `".$this->table."` where collection_id = `$id` LIMIT 1";
			$user = $_SESSION['db']->getArray($query);
			
			foreach($user[0] as $k => $v) {
				if(property_exists(get_class($this),$k)) {
					$this->db_fields[] = $k;
					$this->$k = $v;
				}
			}
		} elseif (is_object($obj)) {
			$this->create($obj);
		}
	}
	
	
	public function getList() {
		return $_SESSION['db']->getAll("select * from `".$this->table."` where c_user_id = '".$_SESSION['joel']->user->user_id."' order by c_name");
	}
	
  	/**
	 * expects the fields to be updated as an array:
	 * $obj[fields] = array("u_name" => "Charles Bronson"[,...]);
	 */
	function update ($obj) {
		if(is_object($obj)) {
			$set = array();
			foreach($obj as $k => $v) {
				if(property_exists(get_class($this),$k)) {
					$this->$k = $v;
					if(in_array($k,$this->db_fields)) {
						$set[] = "`".$k."` = '".mysql_escape_string($v)."'";
					}
				}
			}
			
			$query = "update `".$this->table."` set ".implode($set,", ")." where collection_id = ".$this->collection_id." LIMIT 1";
			$_SESSION['db']->execute($query) or die ($_SESSION['db']->ErrorMsg());
			return true;		
		} else {
			return false;
		}
	}
	
	function create($obj) {
		$error = array();
		if($obj->name == '') $error[] = "name";
		
		// check if user exists
		if(count($error) == 0) {
			$info = "";
			$name = mysql_real_escape_string($obj->name);
			if(isset($obj->info)) $info = mysql_real_escape_string($obj->info);
			
			$query = "INSERT INTO `".$this->table."` SET `c_name`='$name', `c_info`='$info', `c_user_id` = ".$_SESSION['joel']->user->user_id;
			$result = $_SESSION['db']->execute($query);
			if($result) {
				$this->collection_id =  $_SESSION['db']->insert_id();
				$this->c_name = $name;
				$this->c_info = $info;
				$this->c_user = $_SESSION['joel']->user->user_id;
				
				$result = array();
				$result['data'] = $this->getData();
				$result['result'] = 'success';
			}  else {
				$result = array('error' => $_SESSION['db']->ErrorMsg(), 'result' => 'failure');
			}
		} else {
			$result = array('error' => 'Name missing', 'result' => 'failure');
		}
		
		$_SESSION['joel']->jsonResponse($result);
	}
	
	function getData() {
		$return = array();
		$private = array('db_fields','table');
		foreach($this as $e => $v) {
			if(!in_array($e, $private)) {
				$return[$e] = $v;
			}
		}
		
		return $_SESSION['joel']->plugins_apply('_collection_getData',$return);
	}
	
	function delete($id) {
		if(intval($id)) {
			$projects = new Project();
			$projectslist = $projects->getBycollectionId($id);
			if($projectslist) {
				$project = $projects($id);
				if($project) {
					$project->delete();
				}
			} 
			// delete tasklists
						
			
		}
	}
}